package soul.mq;

import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//@Configuration
public class MQConsumerConfig {

    @Bean
    MessageListenerAdapter listenerAdapter(MQMessageListener receiver) {
        return new MessageListenerAdapter(receiver ,"onMessage");
    }

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses("127.0.0.1:5672");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        connectionFactory.setPublisherConfirms(true); //必须要设置
        return connectionFactory;
    }

    @Bean
    SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
                                             MessageListenerAdapter listenerAdapter
    ) {

        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();

        container.setConnectionFactory(connectionFactory);
        String[] subcribeQueue = {"abc"};
        if(subcribeQueue.length>0) {
            Queue[] queues = new Queue[subcribeQueue.length];
            int i = 0;
            for (String s : subcribeQueue) {
                queues[i] = new Queue(s);
                i++;
            }
            container.setQueues(queues);
        }
        container.setAutoStartup(false);
        container.setPrefetchCount(10);
        container.setMessageListener(listenerAdapter);
        return container;
    }
}
